#!/bin/bash

# 颜色变量设置
GREEN='\033[0;32m'
BLUE='\033[0;34m'
YELLOW='\033[0;33m'
RED='\033[0;31m'
NC='\033[0m' # 无颜色

# 打印带颜色的消息函数
print_message() {
    echo -e "${2}[$(date '+%Y-%m-%d %H:%M:%S')] $1${NC}"
}

# 检查上一个命令是否成功执行
check_status() {
    if [ $? -eq 0 ]; then
        print_message "$1成功" "${GREEN}"
    else
        print_message "$1失败，脚本终止" "${RED}"
        exit 1
    fi
}

# 检查是否已安装Docker和Docker Compose
if ! command -v docker &> /dev/null; then
    print_message "错误: Docker未安装，请先安装Docker" "${RED}"
    exit 1
fi

if ! command -v docker-compose &> /dev/null; then
    print_message "错误: Docker Compose未安装，请先安装Docker Compose" "${RED}"
    exit 1
fi

# 工作目录设置
WORK_DIR=$(pwd)
print_message "工作目录: $WORK_DIR" "${BLUE}"

# 确保在项目根目录
if [ ! -f "docker-compose.yml" ] || [ ! -f "Dockerfile" ]; then
    print_message "错误: 当前目录不是项目根目录，请切换到包含docker-compose.yml和Dockerfile的目录" "${RED}"
    exit 1
fi

# 拉取最新代码
print_message "拉取最新代码..." "${YELLOW}"
git pull
check_status "代码拉取"

# 停止并删除旧容器
print_message "停止并移除旧容器..." "${YELLOW}"
docker-compose down
check_status "容器停止"

# 清理未使用的镜像
print_message "清理无用的镜像..." "${YELLOW}"
docker image prune -f
check_status "镜像清理"

# 构建新镜像
print_message "构建新镜像..." "${YELLOW}"
docker-compose build
check_status "镜像构建"

# 启动新容器
print_message "启动新容器..." "${YELLOW}"
docker-compose up -d
check_status "容器启动"

# 检查容器状态
print_message "检查容器状态..." "${YELLOW}"
docker-compose ps
check_status "状态检查"

# 查看容器日志
print_message "显示容器日志..." "${YELLOW}"
docker-compose logs --tail=50
check_status "日志显示"

print_message "部署完成！容器现已成功更新并启动" "${GREEN}" 